package cn.im.qywx.wx.component.wakeon.util;

import lombok.extern.slf4j.Slf4j;
import org.thymeleaf.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * @Description: ping ip，检测是否开机
 */
@Slf4j
public class Ping {
	

	public static boolean socketConn(String ip){
		
		if(!StringUtils.isEmpty(ip)){
			try {
				Socket s =new Socket(); 
				 SocketAddress address = new InetSocketAddress(ip, 3389);
				 s.connect(address,2000);
				 log.info(ip + ": "+s.isConnected());
				 s.close();
				 return true;
			} catch (Exception e) {
				log.info(ip + ": connection time out.");
			}
		}else{
			log.info("ip is blank.");
		}
		return false;
	}

		public static boolean pingFunction_1(String deviceIp){
	
			String line = "";
			String returnMsg = "";
			boolean flag = false;
			try{
		
				log.info("1");
				Process pro = Runtime.getRuntime().exec("telnet " + deviceIp + " 3389");
			
				log.info("2");
				BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			
				log.info("3");
				while ((line = buf.readLine()) != null){
					log.info("4");
					log.info(line);
					returnMsg += line;
				}
				log.info(returnMsg);
				if(returnMsg.indexOf("Unreachable") != -1 || returnMsg.indexOf("100% packet loss") != -1){
					flag = false;
				}else{
					flag = true;
				}
		
			}catch (Exception ex){
				ex.printStackTrace();
			}
			return flag;
		}

	/**
	 * @Description: 检测IP是否可以ping通
	 * @param ipAddress
	 *            ip地址
	 * @return boolean true 可以
	 */
	public static boolean ping(String ipAddress) {
		int timeOut = 3000; // 超时应该在3钞以上
		boolean status = false;
		try {
			status = InetAddress.getByName(ipAddress).isReachable(timeOut);// 当返回值是true时，说明host是可用的，false则不可
			log.info("ping:" + ipAddress + "    result:" + status);
		} catch (Exception e) {
			log.info(" ping ip excepiton. IP:" + ipAddress);
			e.printStackTrace();
		}
		return status;
	}

}
